<?php

class ProductController extends Controller
{
	public function actionIndex()
	{
		$criteria = new CDbCriteria(array(
				'condition' => 'status=1',
				'order' => 'create_time DESC',
				//'with'=>'commentCount',
		));

		$cat = null;
		if(isset($_GET['cid']))
		{
			$criteria->addSearchCondition('cat_id',$_GET['cid']);
			$cat = ProductCat::model()->findByPk($_GET['cid']);
		}


		$dataProvider = new CActiveDataProvider('Product', array(
				'pagination' => array(
						'pageSize' => Yii::app()->params['postsPerPage'],
				),
				'criteria' => $criteria,
		));


		$this->render('index',array('dataProvider'=>$dataProvider,'cat'=>$cat));
	}

	public function actionView($id)
	{
		$product = Product::model()->findByPk($id);
		$product->view++;
		$product->update(array('view'));
		$comment = $this->newComment($product);
		
		$criteria = new CDbCriteria(array(
				'condition' => 'status=1 AND id <> '.$id.' AND cat_id = '.$product->cat_id,
				'order' => 'id DESC',
				'limit'=>4,
		));
		
		$others = new CActiveDataProvider('Product', array(
				'pagination' => array(
						'pageSize' => Yii::app()->params['postsPerPage'],
				),
				'criteria' => $criteria,
		));
		
		$this->render('view', array('model' => $product, 'comment' => $comment,'others'=>$others));
	}

    /**
     * @param $product
     * @internal param \News $news
     * @return Comments
     */
	protected function newComment($product)
	{
		$comment = new Comments;

		if (!Yii::app()->user->isGuest)
		{
			$comment->user_id = (int)Yii::app()->user->id;

		}


		if (isset($_POST['ajax']) && $_POST['ajax'] === 'comments-form')
		{
			echo CActiveForm::validate($comment);
			Yii::app()->end();
		}


		if (isset($_POST['Comments']))
		{
			$comment->attributes = $_POST['Comments'];
			if ($product->addComment($comment))
			{
				Yii::app()->user->setFlash('commentSubmitted', 'Cảm ơn bạn đã bình luận.');
				$this->refresh();
			}
		}

		return $comment;
	}


	public function actionAddcart($id)
	{
		$this->layout = 'no';

		//$session = new CHttpSession();

		$cart = array();

		if(isset(Yii::app()->session['Cart']) && Yii::app()->session['Cart'])
		{
			$cart = unserialize(Yii::app()->session['Cart']);
			$exist = false;
				
			foreach($cart as &$c)
			{
				if($c['id'] == $id)
				{
					$c = array(
							'id'=> $id,
							'count'=>1,
					);
						
					$exist = true;
				}
			}
				
			if(!$exist)
			{
				$cart[] = array(
						'id'=> $id,
						'count'=>1,
				);
			}
		}
		else
		{
			$cart[] = array(
					'id'=> $id,
					'count'=>1,
			);
		}


		Yii::app()->session['Cart'] = serialize($cart);

		header("Content-Type: application/json");
		echo json_encode(array('success'=>1));
	}

	public function actionCart()
	{
		//$session = new CHttpSession();

		$cart = array();

		$items = array();

		if(isset(Yii::app()->session['Cart']) && Yii::app()->session['Cart'])
		{
				
			$cart = unserialize(Yii::app()->session['Cart']);

			foreach($cart as $item){
				$items[] = array('item'=>Product::model()->findByPk($item['id']),'count'=>$item['count']);
			}
		}

		$this->render('cart',array('items'=>$items));
	}

	public function actionRemove($id)
	{
		if(isset(Yii::app()->session['Cart']) && Yii::app()->session['Cart'])
		{

			$cart = unserialize(Yii::app()->session['Cart']);

			for($i = 0;$i<count($cart);$i++){
				if($cart[$i]['id'] == $id){
					unset($cart[$i]);
				}
			}
				
			Yii::app()->session['Cart'] = serialize($cart);
				
			header("Content-Type: application/json");
			echo json_encode(array('success'=>1));
		}
	}

	public function actionChangenum()
	{
		$id = (int)$_GET['id'];
		$count = (int)$_GET['count'];

		if($id && $count && isset(Yii::app()->session['Cart']) && Yii::app()->session['Cart'])
		{

			$cart = unserialize(Yii::app()->session['Cart']);

			foreach($cart as &$item){
				if($item['id'] == $id){
					$item['count'] = $count;
				}
			}

			Yii::app()->session['Cart'] = serialize($cart);

			header("Content-Type: application/json");
			echo json_encode(array('success'=>1));
		}
	}

	public function actionPay()
	{
		if(Yii::app()->user->isGuest)
		{
			Yii::app()->user->loginRequired();
		}

		$model= Customer::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));

		if($model === null)
		{
			$model = new Customer();
		}
		/* unset($model->attributes);
		 $model->user_id  = Yii::app()->user->id; */
		// uncomment the following code to enable ajax-based validation
		/*
		 if(isset($_POST['ajax']) && $_POST['ajax']==='customer-_customer-form')
		 {
		echo CActiveForm::validate($model);
		Yii::app()->end();
		}
		*/

		if(isset($_POST['Customer']))
		{
			$model->attributes=$_POST['Customer'];
				
			if($model->validate() && $model->save())
			{
				$this->redirect($this->createUrl('cartdetail'));
			}
		}

		$this->render('_customer',array('model'=>$model));
	}

	public function actionCartdetail()
	{
		if(Yii::app()->user->isGuest)
		{
			Yii::app()->user->loginRequired();
		}

		$cart = new Cart();
	
		$items = array();
		
		if(isset(Yii::app()->session['Cart']) && Yii::app()->session['Cart'])
		{
				
			$cart = unserialize(Yii::app()->session['Cart']);

			foreach($cart as $item){
				$items[] = array('item'=>Product::model()->findByPk($item['id']),'count'=>$item['count']);
			}
		}

		$customer = Customer::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
		
		$this->render('cart_detail',array('items'=>$items,'customer'=>$customer));
	}

	public function actionComplete()
	{
		if(Yii::app()->user->isGuest)
		{
			Yii::app()->user->loginRequired();
		}

		$cart = new Cart();

		if(isset(Yii::app()->session['Cart']) && Yii::app()->session['Cart'])
		{
			$cart->cart_content = Yii::app()->session['Cart'];
		}

		$customer = Customer::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
		if($customer !== null)
		{
			$cart->customer_id = $customer->id;
		}

		if($cart->save())
		{
			Yii::app()->user->setFlash('buy_complete', 'Bạn đã đặt hàng thành công. Mã đơn hàng của bạn là <b>'.$cart->id.'</b>. Để nhận hàng và thanh toán vui lòng liên hệ trực tiếp với LNT.');
			unset(Yii::app()->session['Cart']);
		}
		$this->render('complete');
	}

}